import {inject, reactive} from "vue";

export function createPinia() {
  return {
    install(app) {
      const store = reactive({})
      app.provide('setSubStore', (storeName, subStore) => {
        store[storeName] = subStore
        const $patch = (options) => {
          for (const optionsKey in options) {
            store[storeName][optionsKey] = options[optionsKey]
          }
        }
        store[storeName].$patch = $patch
      });
      app.provide('piniaStore',store)
    }
  }
}

export function defineStore(storeName, options) {
  const store = reactive({});
  const state = options.state();
  const actions = options.actions;
  for (let key in state) {
    store[key] = state[key]
  }
  for (const actionsKey in actions) {
    store[actionsKey] = actions[actionsKey].bind(store)
  }
  return function () {
    // return store
    const piniaStore = inject('piniaStore')
    if (!piniaStore[storeName]){
      const setSubStore = inject('setSubStore')
      setSubStore(storeName,store)
    }
    return piniaStore[storeName]
  }
}
